import { defineStore } from 'pinia';
import { ref } from 'vue';
import { Message } from '@arco-design/web-vue';
import supplierApi from '@/api/supplier';

export const useSupplierStore = defineStore('supplier', () => {
  const loading = ref(false);
  const suppliers = ref([]);
  const supplierDetail = ref(null);
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
  });

  /**
   * 获取供应商列表
   * @param {Object} params - 查询参数
   * @returns {Promise} 请求结果
   */
  async function getSupplierList(params = {}) {
    loading.value = true;
    console.log('调用getSupplierList，参数:', params);
    
    try {
      // 尝试调用API
      const response = await supplierApi.getSupplierList({
        page: pagination.value.current,
        page_size: pagination.value.pageSize,
        ...params
      });
      
      console.log('API响应详情:', response);
      
      // 修复前后端数据结构不匹配问题
      if (response && response.code === 0) {
        // 服务器端有数据，但可能list为空数组
        if (response.data && response.data.list) {
          suppliers.value = response.data.list;
        } else {
          suppliers.value = [];
        }
        
        // 更新分页信息
        pagination.value.total = response.data.total || 0;
        pagination.value.current = response.data.page || pagination.value.current;
        pagination.value.pageSize = response.data.size || pagination.value.pageSize;
        
        // 如果成功获取到数据，显示成功提示
        if (suppliers.value && suppliers.value.length > 0) {
          console.log('成功获取到供应商数据，数量:', suppliers.value.length);
        } else {
          console.warn('API返回成功，但数据为空');
        }
        
        return {
          success: true,
          data: {
            list: suppliers.value,
            pagination: pagination.value
          }
        };
      } else {
        // 服务器返回错误
        console.error('服务器返回错误:', response.message);
        Message.error(response.message || '获取供应商列表失败');
        return {
          success: false,
          message: response.message || '获取供应商列表失败'
        };
      }
    } catch (error) {
      // 网络错误或其他异常
      console.error('获取供应商列表失败:', error);
      Message.error('获取供应商列表失败: ' + (error.message || '未知错误'));
      
      return {
        success: false,
        message: error.message || '未知错误'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 获取供应商详情
   * @param {Number} id - 供应商ID
   * @returns {Promise} 请求结果
   */
  async function getSupplierDetail(id) {
    loading.value = true;
    try {
      const response = await supplierApi.getSupplierDetail(id);
      
      if (response.code === 0) {
        supplierDetail.value = response.data;
        return {
          success: true,
          data: supplierDetail.value
        };
      } else {
        Message.error(response.message || '获取供应商详情失败');
        return {
          success: false,
          message: response.message || '获取供应商详情失败'
        };
      }
    } catch (error) {
      console.error('获取供应商详情失败:', error);
      Message.error('获取供应商详情失败，请稍后重试');
      return {
        success: false,
        message: '网络错误，请稍后重试'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 创建供应商
   * @param {Object} data - 供应商数据
   * @returns {Promise} 请求结果
   */
  async function createSupplier(data) {
    loading.value = true;
    try {
      const response = await supplierApi.createSupplier(data);
      
      if (response.code === 0) {
        Message.success('创建供应商成功');
        return {
          success: true,
          data: response.data
        };
      } else {
        Message.error(response.message || '创建供应商失败');
        return {
          success: false,
          message: response.message || '创建供应商失败'
        };
      }
    } catch (error) {
      console.error('创建供应商失败:', error);
      Message.error('创建供应商失败，请稍后重试');
      return {
        success: false,
        message: '网络错误，请稍后重试'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 更新供应商
   * @param {Number} id - 供应商ID
   * @param {Object} data - 供应商数据
   * @returns {Promise} 请求结果
   */
  async function updateSupplier(id, data) {
    loading.value = true;
    try {
      const response = await supplierApi.updateSupplier(id, data);
      
      if (response.code === 0) {
        Message.success('更新供应商成功');
        return {
          success: true,
          data: response.data
        };
      } else {
        Message.error(response.message || '更新供应商失败');
        return {
          success: false,
          message: response.message || '更新供应商失败'
        };
      }
    } catch (error) {
      console.error('更新供应商失败:', error);
      Message.error('更新供应商失败，请稍后重试');
      return {
        success: false,
        message: '网络错误，请稍后重试'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 删除供应商
   * @param {Number} id - 供应商ID
   * @returns {Promise} 请求结果
   */
  async function deleteSupplier(id) {
    loading.value = true;
    try {
      const response = await supplierApi.deleteSupplier(id);
      
      if (response.code === 0) {
        Message.success('删除供应商成功');
        return {
          success: true
        };
      } else {
        Message.error(response.message || '删除供应商失败');
        return {
          success: false,
          message: response.message || '删除供应商失败'
        };
      }
    } catch (error) {
      console.error('删除供应商失败:', error);
      Message.error('删除供应商失败，请稍后重试');
      return {
        success: false,
        message: '网络错误，请稍后重试'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 导入供应商数据
   * @param {FormData} formData - 包含供应商数据的表单
   * @returns {Promise} 请求结果
   */
  async function importSuppliers(formData) {
    loading.value = true;
    try {
      const response = await supplierApi.importSuppliers(formData);
      
      if (response.code === 0) {
        Message.success('导入供应商成功');
        return {
          success: true,
          data: response.data
        };
      } else {
        Message.error(response.message || '导入供应商失败');
        return {
          success: false,
          message: response.message || '导入供应商失败'
        };
      }
    } catch (error) {
      console.error('导入供应商失败:', error);
      Message.error('导入供应商失败，请稍后重试');
      return {
        success: false,
        message: '网络错误，请稍后重试'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 导出供应商数据
   * @param {Object} params - 导出参数
   * @returns {Promise} 请求结果
   */
  async function exportSuppliers(params = {}) {
    loading.value = true;
    try {
      const response = await supplierApi.exportSuppliers(params);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('导出供应商失败:', error);
      Message.error('导出供应商失败，请稍后重试');
      return {
        success: false,
        message: '网络错误，请稍后重试'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 设置分页
   * @param {Number} page - 页码
   * @param {Number} pageSize - 每页数量
   */
  function setPagination(current, pageSize) {
    pagination.value.current = current;
    pagination.value.pageSize = pageSize;
  }

  /**
   * 获取所有供应商（用于下拉选择）
   * @returns {Promise} 请求结果
   */
  async function getAllSuppliers() {
    try {
      const response = await supplierApi.getSupplierList({ page_size: 9999 });
      
      if (response.code === 0) {
        // 更新供应商状态，确保数据存储到 suppliers 中
        suppliers.value = response.data.list || [];
        return { success: true, data: response.data.list || [] };
      }
      
      return { success: false, message: response.message, data: [] };
    } catch (error) {
      console.error('获取所有供应商出错:', error);
      return { success: false, message: error.message || '未知错误', data: [] };
    }
  }

  return {
    loading,
    suppliers,
    supplierDetail,
    pagination,
    getSupplierList,
    getSupplierDetail,
    createSupplier,
    updateSupplier,
    deleteSupplier,
    importSuppliers,
    exportSuppliers,
    setPagination,
    getAllSuppliers
  };
}); 